<template>
  <div class="taskAdd">
    <div class="details">
      <div class="details-header-button">
        <!-- <el-tooltip class="item" effect="dark" content="子任务" placement="right">
            <i class="iconfont icon-tianjiazirenwu-copy details-header-button-icon" @click="subtaskClick"></i>
        </el-tooltip> -->

      </div>
    </div>
    <div class="taskAdd-content">
      <span class="taskAdd-header">修改任务</span>
      <div class="taskAdd-row">
        <el-input class="taskAdd-row-title" placeholder="请输入标题" size="medium" v-model="taskForm.name" clearable>
        </el-input>
        <el-select ref="elSelect" class="taskAdd-row-type" v-model="taskForm.taskType" size="medium" clearable
                   placeholder="请选择任务类型">
          <el-option v-for="item in taskTypeFrom" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="taskAdd-row">
        <!-- <personInCharge ref="personInCharge" :projId='taskForm.projId' @personChoose="personChoose" :master="taskForm.masterSysUser" :userList="taskForm.userList" class="taskAdd-row-personInCharge"></personInCharge> -->
        <project class="task-project" :name="taskForm.projName" @projectSelect="projectSelect"></project>
        <priority class="task-warehouse" :data="taskForm.matrix" @priorityChoose="priorityChoose"></priority>
        <el-select class="task-milepost" @visible-change='visiblechange' v-model="taskForm.mptName" clearable
                   size="medium" placeholder="请选择里程碑" value-key="mptId" :filter-method="remoteMpt" filterable
                   @change="selectMpt">
          <el-option v-for="item in milepostForm" :key="item.mptId" :label="item.name" :value="item">
          </el-option>
        </el-select>
        <!-- <span style="color:rgb(230,180,169)" v-if="milepostForm.length==0&&this.taskForm.projId!=''">(该项目没有里程碑)</span> -->
      </div>
      <selectRoleTwo type='warehouse' :parentProjId='taskForm.projId' selectType='singleChoice'
                     :masterUserId='taskForm.masterUserId' style="width:910px;margin-top:20px"
                     @selectsuccess='selectsuccess'></selectRoleTwo>
      <selectmember type='warehouse' selectType='multipleChoice' :parentProjId='taskForm.projId'
                    :memberList='memberList' style="width:910px;margin-top:20px"
                    @selectsuccess='selectsuccessmamber'></selectmember>
      <div class="task-quillEditor">
        <el-input style="width: 910px;" type="textarea" :rows="6" placeholder="请输入内容" v-model="taskForm.content">
        </el-input>
      </div>
      <div class="task-multipleChoiceTags">
        <multipleChoiceTags :tags="taskForm.tags" @tagChoose="tagChoose" type="01"
                            style="width: 100%;height: 100%"></multipleChoiceTags>
      </div>
      <span class="task-more">更多设置</span>
      <div class="taskAdd-row" v-if="taskForm.status=='00'">
        <span>计划时间：</span>
        <el-date-picker @change="startDateClick" value-format="yyyy-MM-dd" v-model="taskForm.startDate" type="date"
                        size="medium" class="task-date" placeholder="开始日期">
        </el-date-picker>
        <el-date-picker @change="endDateClick" value-format="yyyy-MM-dd" v-model="taskForm.endDate" type="date"
                        size="medium" class="task-date" placeholder="截止日期">
        </el-date-picker>
        <!-- <el-input placeholder="预计工时（小时）" v-model="taskForm.taskTime" type="number" size="medium" class="task-time">
        </el-input> -->
      </div>
      <!-- <div class="taskAdd-row">
          <span>实际时间：</span>
          <el-date-picker value-format="yyyy-MM-dd" v-model="taskForm.workStartDate" type="date" size="medium" class="task-date" placeholder="实际开始日期">
          </el-date-picker>
          <el-date-picker  value-format="yyyy-MM-dd" v-model="taskForm.workEndDate" type="date" size="medium" class="task-date" placeholder="实际截止日期">
          </el-date-picker>
      </div> -->
      <div class="task-subtask task-more">
        <div class="task-subtask-header">
          <span class="task-subtask-title">子任务</span>
          <i class="task-subtask-icon el-icon-plus" @click="subtaskClick"></i>
        </div>
        <taskIndex :taskForm="subTaskData"></taskIndex>

        <div class="task-subtask-itemTwo" v-for="(items,index) in subtaskForm">
          <div style="display:flex;">
            <el-input class="mr10 task-subtask-item-title" v-model="items.subtaskTitle" placeholder="请输入子任务标题"
                      size="medium"></el-input>
            <!-- <director @dirctorChoose="dirctorChoose" :projId="taskForm.projId" ></director> -->
            <el-date-picker value-format="yyyy-MM-dd" v-model="items.startDate" type="date" size="medium"
                            class="task-date" placeholder="开始日期">
            </el-date-picker>
            <el-date-picker style="margin-right:0px" value-format="yyyy-MM-dd" v-model="items.endDate" type="date"
                            size="medium" class="task-date" placeholder="截止日期">
            </el-date-picker>
          </div>
          <selectRoleTwo style="margin-top:10px" type='warehouse' :parentProjId='taskForm.projId'
                         selectType='singleChoice' @selectsuccess='dirctorChoose'></selectRoleTwo>
          <selectmember style="margin-top:15px" type='warehouse' selectType='multipleChoice'
                        :parentProjId='taskForm.projId' @selectsuccess='subMemberChoose'></selectmember>
          <el-button class="mr10" size="medium" type="primary" @click="subtaskSave(index)">保存</el-button>
          <el-button class="ml0" size="medium" @click="subtaskCancel(index)">取消</el-button>
        </div>
      </div>
      <singlefileUpload style="width:50px" ref="upload" @uploadSave="uploadSave" @returnUrl="returnUrl"
                        :ruleFormdocFilePath='uploadForm' @uploadListDel="uploadListDel">
        <template v-slot:openDialog>
          <!-- <el-tooltip class="item" effect="dark" content="添加附件" placement="right"> -->
          <!-- <i class="details-header-button-icon iconfont icon-fujian-copy"></i> -->
          <!-- <el-button style="width: 100px;" plain>上传附件</el-button> -->
          <div style="display:flex;">
            <span class="task-subtask-title">附件</span>
            <i class="task-subtask-icon iconfont icon-fujian-copy"></i>

          </div>
          <!-- </el-tooltip> -->
        </template>
      </singlefileUpload>
      <div class="task-subtask" v-if="taskForm.docList && taskForm.docList.length>0">
        <!-- <div class="task-subtask-header">
            <span class="task-subtask-title">附件（ {{taskForm.docList.length}} ）</span>
        </div> -->
        <div class="task-subtask-item" v-for="(items,index) in taskForm.docList">
          <i class="iconfont icon-fujian-copy task-enclosure-icon"></i>
          <span class="task-enclosure-title">{{ items.name }}</span>
          <span class="task-enclosure-size">上传于 {{ items.createTime }}</span>
          <div class="task-enclosure-member">
            <span class="task-enclosure-member-title">{{ items.createName }}</span>
          </div>
          <i class="el-icon-delete task-enclosure-del-icon" @click="enclosureCancel(items,index)"></i>
        </div>
      </div>
      <el-button class="task-save" size="medium" type="primary" @click="btnUpdate">提交</el-button>
    </div>
  </div>
</template>
<script>
import personInCharge from "../../../components/select/personInCharge";
import quillEditor from "../../../components/quillEditor/index";
import multipleChoiceTags from "../../../components/select/multipleChoiceTags";
import priority from "../../../components/select/priority";
import chooseStatusBotton from "../../../components/chooseStatus/button";
import director from "../../../components/select/director";
import singlefileUpload from "@/components/upload/singlefileUpload";
import {save, update, queryById, getTreeData} from "@/api/task";
import {save as saveDoc, softDelete, list as docList} from "@/api/doc.js";
import taskIndex from "@/components/task/index.vue";
import project from "@/components/select/project.vue";
import {list as gitList} from "@/api/git.js";
import {list as mptList} from "@/api/mpt.js";
import selectmember from "@/components/screen/selectmember";
import selectRoleTwo from "@/components/screen/selectRoleTwo";
import utils from "@/utils/utils";

export default {
  name: "Edit",
  data() {
    return {
      taskTypeFrom: [
        {
          value: "00",
          label: "需求",
        },
        {
          value: "01",
          label: "设计",
        },
        {
          value: "02",
          label: "开发",
        },
        {
          value: "04",
          label: "测试",
        },
        {
          value: "05",
          label: "缺陷",
        },
        {
          value: "06",
          label: "其他",
        },
      ],
      taskId: "",
      taskForm: {
        tags: [],
      },
      subTaskData: [],
      warehouse: [],
      milepostForm: [],
      taskTitle: "",
      taskProject: "",
      taskWarehouse: "",
      taskMilepost: "",
      taskBranch: "",
      taskStartTime: "",
      taskClosingDate: "",
      taskTime: "",
      subtaskForm: [],
      associatedTaskFrom: [],
      enclosureForm: [],
      directorMasterUserId: "",
      startPickerOptions: {},
      endPickerOptions: {},
      substartPickerOptions: {},
      subendPickerOptions: {},
      memberList: [],
      subUserList: [],
      uploadForm: [],
    };
  },
  components: {
    personInCharge,
    quillEditor,
    multipleChoiceTags,
    priority,
    chooseStatusBotton,
    director,
    singlefileUpload,
    taskIndex,
    project,
    selectmember,
    selectRoleTwo,
  },
  created() {
    this.taskId = this.$route.query.id;
    this.taskQuery();
  },
  mounted() {
  },
  methods: {
    // 控制选择时间范围
    endDateClick(data) {
      this.startPickerOptions = {
        disabledDate(time) {
          return time.getTime() > new Date(data);
        },
      };
    },
    endDatesubtaskClick(data) {
      this.substartPickerOptions = {
        disabledDate(time) {
          return time.getTime() > new Date(data);
        },
      };
    },
    startDateClick(data) {
      console.log(data);
      this.endPickerOptions = {
        disabledDate(time) {
          return time.getTime() < new Date(data);
        },
      };
    },
    startDatesubtaskClick(data) {
      console.log(data);
      this.subendPickerOptions = {
        disabledDate(time) {
          return time.getTime() < new Date(data);
        },
      };
    },
    // 任务详情
    taskQuery() {
      var _this = this;
      queryById({
        id: _this.taskId,
      }).then((res) => {
        _this.taskForm = res.data;
        _this.taskForm.userList.forEach(function (item) {
          _this.memberList.push(item.userId);
        });
        if (_this.taskForm.startDate) {
          _this.endPickerOptions = {
            disabledDate(time) {
              return (
                  time.getTime() <
                  new Date(_this.taskForm.startDate)
              );
            },
          };
        }
        if (_this.taskForm.endDate) {
          this.startPickerOptions = {
            disabledDate(time) {
              return (
                  time.getTime() >
                  new Date(_this.taskForm.endDate)
              );
            },
          };
        }
        // _this.loadMptList();
        _this.subTaskQuery();
      });
    },
    // 修改任务
    btnUpdate() {
      var _this = this;
      if (!_this.taskForm.name) {
        _this.$message.error("请输入任务标题");
        return;
      }
      // if (!_this.taskForm.content) {
      //     _this.$message.error("请输入任务简介");
      //     return;
      // }
      if (!this.taskForm.projId) {
        _this.$message.error("请选择关联项目");
        return;
      }
      update(_this.taskForm).then((res) => {
        this.$EventBus.$emit("taskUpate");
        _this.$store
            .dispatch("tagsView/delView", _this.$route)
            .then(({visitedViews}) => {
              _this.$router.push({
                path: "/task/details",
                query: {id: _this.taskId},
              });
            }); // 关闭当前tab回到列表
      });
    },
    // 查询子任务
    subTaskQuery() {
      var _this = this;
      var level = Number(_this.taskForm.taskLevel) + 1;
      getTreeData({parentId: _this.taskId, level}, false).then(
          (res) => {
            const {data} = res;
            _this.subTaskData = data.data;
          }
      );
    },
    // 新增子任务
    subtaskClick() {
      let data = {
        subtaskTitle: "",
        personInCharge: "",
        startDate: "",
        endDate: "",
      };
      this.subtaskForm.push(data);
    },
    subtaskSave(index) {
      let _this = this;
      let subTakeForm = {
        name: _this.subtaskForm[index].subtaskTitle,
        parentTaskId: _this.taskId,
        taskLevel: "",
        taskLevelCode: "",
        masterUserId: _this.directorMasterUserId, //负责人id
        matrix: "00",
        startDate: _this.subtaskForm[index].startDate,
        endDate: _this.subtaskForm[index].endDate,
        taskType: _this.taskForm.taskType,
        projId: _this.taskForm.projId,
        userList: _this.subUserList,
      };
      if (!_this.subtaskForm[index].startDate) {
        _this.$message.error("请输入子任务开始时间");
        return;
      }
      if (!_this.subtaskForm[index].endDate) {
        _this.$message.error("请输入子任务结束时间");
        return;
      }
      if (!subTakeForm.name) {
        _this.$message.error("请输入子任务标题");
        return;
      }
      if (!_this.directorMasterUserId) {
        _this.$message.error("请选择负责人");
        return;
      }
      console.log(subTakeForm);
      save(subTakeForm).then((res) => {
        console.log(res);
        _this.subtaskForm.splice(index, 1);
        _this.subTaskQuery();
      });
    },
    subtaskCancel(index) {
      this.subtaskForm.splice(index, 1);
    },
    // 项目选择
    projectSelect(data) {
      console.log(data);
      if (this.taskForm.projId == data.projId) {
        return;
      }
      this.taskForm.projId = data.projId;
      this.taskForm.projName = data.name;
      this.taskForm.masterSysUser = null;
      this.taskForm.userList = [];
    },
    // 仓库选择
    loadGitList(data) {
      var _this = this;
      var name = "";
      if (data) {
        name = data;
      } else {
        name: "";
      }
      gitList({
        current: 1,
        size: 20,
        name: name,
      }).then((res) => {
        console.log(res);
        _this.warehouse = res.data.records;
      });
    },
    // 仓库搜索
    remoteWarehouse(query) {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      this.timer = setTimeout(() => {
        this.loadGitList(query);
      }, 500);
    },
    // 选择仓库
    selectWarehouse(data) {
      console.log(data);
      this.taskForm.gitId = data.gitId;
      this.taskForm.gitName = data.name;
    },
    visiblechange(data) {
      console.log(data);
      if (data == true) {
        this.loadMptList();
      }
    },
    // 里程碑选择
    loadMptList(data) {
      var _this = this;
      var name = "";
      if (data) {
        name = data;
      } else {
        name: "";
      }
      mptList(
          {
            current: 1,
            size: 20,
            name: name,
            projId: _this.taskForm.projId,
          },
          false
      ).then((res) => {
        console.log(res);
        _this.milepostForm = res.data.records;
      });
    },
    // 里程碑搜索
    remoteMpt(query) {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      this.timer = setTimeout(() => {
        this.loadMptList(query);
      }, 500);
    },
    // 选择里程碑
    selectMpt(data) {
      console.log(data);
      this.taskForm.mptId = data.mptId;
      this.taskForm.mptName = data.name;
    },
    // 选择子任务负责人
    dirctorChoose(data) {
      console.log(data);
      console.log("子任务");
      this.directorMasterUserId = "";
      if (data.length > 0) {
        console.log("jinlai");
        this.directorMasterUserId = data[0].userId;
      }
    },
    // 选择子任务成员
    subMemberChoose(data) {
      console.log(data);
      if (!utils.isNull(data)) {
        this.subUserList = [];
        let userArrat = data.split(",");
        userArrat.forEach((item) => {
          let uers = {userId: item};
          this.subUserList.push(uers);
        });
      } else {
        this.subUserList = [];
      }
    },
    // 选择负责人/协助人
    // personChoose(person, collaborators) {
    //     console.log(person);
    //     console.log(collaborators);
    //     if (person) {
    //         this.taskForm.masterUserName = person.userName;
    //         this.taskForm.masterUserId = person.userId;
    //     }
    //     this.taskForm.userList = collaborators;
    // },
    associatedTaskClick() {
      var data = {
        task: "",
        type: "",
        order: "",
        relyOn: "",
      };
      this.associatedTaskFrom.push(data);
    },
    associatedTaskSave() {
      this.associatedTaskFrom.splice(index, 1);
    },
    associatedTaskCancel(index) {
      this.associatedTaskFrom.splice(index, 1);
    },
    enclosureCancel(item, index) {
      var _this = this;
      console.log(item);
      softDelete({ids: item.docId}).then((res) => {
        _this.taskForm.docList.splice(index, 1);
      });
    },
    uploadListDel(index) {
      this.uploadForm.splice(index, 1);
    },
    returnUrl(data) {
      var docFilePath = {
        fileName: data.name,
        fileUrl: data.url,
      };
      this.uploadForm.push(docFilePath);
    },
    uploadSave(val) {
      console.log("data--", val);
      let _this = this;
      // var docFilePath = [
      //     {
      //         fileUrl: val.url,
      //         fileName: val.name,
      //     },
      // ];
      let data = {
        name: val.name,
        docFilePath: this.uploadForm,
        docType: "01",
        docTypeId: _this.taskForm.taskId,
        status: "00",
      };
      saveDoc(data).then((res) => {
        console.log(res);
        _this.taskFormListClick()
        _this.uploadForm = [];
        // _this.taskQuery();
        _this.$refs.upload.sucessClick();
      });
    },
    tagChoose(data) {
      console.log(data);
      this.taskForm.tags = data;
    },
    selectsuccess(data) {
      if (data.length > 0) {
        this.taskForm.masterUserId = data[0].userId;
      }
    },
    selectsuccessmamber(data) {
      if (!utils.isNull(data)) {
        this.taskForm.userList = [];
        let userArrat = data.split(",");
        userArrat.forEach((item) => {
          let uers = {userId: item};
          this.taskForm.userList.push(uers);
        });
      } else {
        this.taskForm.userList = [];
      }
    },
    // 选择优先级
    priorityChoose(data) {
      if (data) {
        this.taskForm.matrix = data.value;
      } else {
        this.taskForm.matrix = "";
      }
    },
    //重新获取附件
    taskFormListClick() {
      var _this = this
      docList({
        current: 1,
        size: 2000,
        docType: "01",
        docTypeId: _this.taskForm.taskId
      }).then((res) => {
        _this.taskForm.docList = res.data.docData;
      });
    },
  },
};
</script>

<style scoped>
.taskAdd {
  box-sizing: border-box;
  height: calc(100vh - 84px);
  display: flex;
  flex-direction: column;
}

.taskAdd-content {
  flex-grow: 1;
  overflow-y: auto;
  padding: 24px;
}

.taskAdd-header {
  font-size: 20px;
  color: #333333;
  font-weight: bold;
}

.taskAdd-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-top: 20px;
}

.taskAdd-row-title {
  width: 700px;
  margin-right: 10px;
}

.taskAdd-row-type {
  width: 200px;
}

.taskAdd-row-personInCharge {
  margin-right: 10px;
}

.task-project {
  width: 160px;
  margin-right: 10px;
}

.task-warehouse {
  width: 160px;
  margin-right: 10px;
}

.task-milepost {
  width: 200px;
}

.task-quillEditor {
  margin-top: 20px;
}

.task-multipleChoiceTags {
  width: 910px;
  margin-top: 20px;
}

.task-more {
  clear: both;
  margin: 16px 0;
  color: #333333;
  font-size: 16px;
  display: block;
  font-weight: bold;
}

.task-date {
  width: 345px;
  margin-right: 10px;
}

.task-time {
  width: 200px;
}

.task-save {
  margin-bottom: 20px;
  margin-top: 20px;
}

.details {
  z-index: 1;
  margin-top: 0;
  flex: none;
  display: flex;
  flex-flow: row wrap;
  align-items: center;
  justify-content: space-between;
  box-shadow: inset 0 -1px 0 0 #dadee3;
  padding: 10px 10px;
  box-sizing: border-box;
}

.details-header-button {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.details-header-button-icon {
  padding: 8px 8px;
  color: #909aaa;
  font-size: 18px;
  margin-left: 10px;
  border-radius: 50%;
}

.task-subtask {
  margin-top: 20px;
}

.task-subtask-header {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 4px;
}

.task-subtask-title {
  /* color: #5f6d84;
  font-size: 12px;
  font-weight: 700;
  margin-right: 5px;
  display: block; */
  clear: both;
  /* margin: 16px 0; */
  color: #333333;
  font-size: 16px;
  display: block;
  font-weight: bold;
}

.task-subtask-icon {
  /* font-size: 12px;
  color: #909aaa;
  display: block; */
  margin-top: 1px;
  color: #333333;
  font-size: 16px;
  display: block;
  font-weight: bold;
  cursor: pointer;
}

.task-subtask-icon:hover {
  color: #2c7ef8;
}

.task-subtask-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-top: 10px;
}

.task-subtask-itemTwo {
  /* display: flex;
  flex-direction: row; */
  /* align-items: center; */
  margin-top: 10px;
}

.mr10 {
  margin-right: 10px;
}

.task-subtask-item-title {
  flex: 1;
}

.task-subtask-item-personInCharge {
  width: 220px;
}

.ml0 {
  margin-left: 0;
}

.task-enclosure-icon {
  /* color: #2e405e;
  font-size: 16px;
  margin-right: 5px;
  font-weight: 700; */
  clear: both;
  /* margin: 16px 0; */
  color: #333333;
  font-size: 16px;
  display: block;
  font-weight: bold;
}

.task-enclosure-title {
  color: #2e405e;
  font-size: 14px;
  margin-right: 16px;
  max-width: 520px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-weight: 700;
}

.task-enclosure-size {
  font-size: 14px;
  font-weight: bold;
  color: #909aaa;
  display: block;
  margin-right: 20px;
}

.task-enclosure-member {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.task-enclosure-member-title {
  max-width: 220px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #2e405e;
  font-size: 14px;
  font-weight: bold;
}

.task-enclosure-del-icon {
  font-size: 14px;
  color: #909aaa;
  margin-left: 20px;
}

/deep/ .el-select {
  margin-bottom: 0px !important;
}

/deep/ .el-input--medium {
  height: 100% !important;
}
</style>
